package view;

import java.awt.event.WindowEvent;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.swing.JPanel;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.demo.PieChartDemo1;
import org.jfree.chart.plot.PiePlot;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;

import control.CConnection;
import control.CFamily;
import control.CGenus;
import control.CSpecies;

public class AnalyticSpeciesDataByFamily extends ApplicationFrame
{
    public AnalyticSpeciesDataByFamily(String title) {
        super(title);
        setContentPane(createDemoPanel());
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
    }
    
    @Override
    public void windowClosing(WindowEvent event) 
    {
    	this.dispose();
    }

    private static PieDataset createDataset() 
    {
    	CConnection cn = new CConnection();

		try {
			cn.createConnection();
			CSpecies cSpecies = new CSpecies(cn);
			
			ArrayList<Object[]> genus = cSpecies.countGroupingByFamilies();
			
			DefaultPieDataset dataset = new DefaultPieDataset();
			for(int i =0;i<genus.size() && i<10 ;i++)
			{
				dataset.setValue(genus.get(i)[0].toString(), Double.parseDouble(genus.get(i)[1].toString()));
			}
			return dataset;
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;   
    }

    private static JFreeChart createChart(PieDataset dataset) {

        JFreeChart chart = ChartFactory.createPieChart(
            "Species by Family - Pie Chart",  // chart title
            dataset,             // data
            true,               // include legend
            true,
            false
        );

        PiePlot plot = (PiePlot) chart.getPlot();
        plot.setSectionOutlinesVisible(false);
        plot.setNoDataMessage("No data available");

        return chart;

    }

    public static JPanel createDemoPanel() {
        JFreeChart chart = createChart(createDataset());
        return new ChartPanel(chart);
    }

    public static void main(String[] args) {
    	AnalyticSpeciesDataByFamily analytics = new AnalyticSpeciesDataByFamily("Species by Family - Pie Chart");
    	analytics.pack();
        RefineryUtilities.centerFrameOnScreen(analytics);
        analytics.setVisible(true);
    }

}
